package util;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.widget.Toast;

public class GPSUtil extends Service implements LocationListener{
	//context of the activity where we will use this service
	private final Context mContext;
	//flag for GPS state
	private boolean isGPSEnabled;
	//flag for Network state
	private boolean isNetworkEnabled;
	private boolean canGetLocation;
	//Location parameters
	private Location location;
	private double longitude;
	private double latitude;
	//the address corresponding to the location
	private Address address;
	
	// The minimum distance to make updates 
	private static final long MIN_DISTANCE_FOR_UPDATES = 10; // 10 meters
	//The minimum time between updates
	private static final long MIN_TIME_BETWEEN_UPDATES = 1000 * 60 * 1; // 1 minute	

	private LocationManager lm;
	//constructor. initialize the context
	public GPSUtil(Context context){
		mContext=context;
		getLocation();
	}
	//get the current location
	public Location getLocation(){
		try{
		lm=(LocationManager) mContext.getSystemService(LOCATION_SERVICE);
		isGPSEnabled=lm.isProviderEnabled(lm.GPS_PROVIDER);
		isNetworkEnabled=lm.isProviderEnabled(lm.NETWORK_PROVIDER);
		if (!isGPSEnabled && !isNetworkEnabled){
			Toast.makeText(mContext, "No location providers available!", Toast.LENGTH_SHORT);
			canGetLocation=false;
		}
		else {
			canGetLocation=true;
			if (isGPSEnabled){
				lm.requestLocationUpdates(lm.GPS_PROVIDER, MIN_TIME_BETWEEN_UPDATES, MIN_DISTANCE_FOR_UPDATES, this);
				if (lm != null){
					location=lm.getLastKnownLocation(lm.GPS_PROVIDER);
					if (location != null){
						latitude=location.getLatitude();
						longitude=location.getLongitude();
						Geocoder coder=new Geocoder(mContext);
						address=coder.getFromLocation(latitude, longitude, 1).get(0);
					}
					else{
						Toast.makeText(mContext, "No location available!", Toast.LENGTH_SHORT);
					}
				}
				else
					Toast.makeText(mContext, "Problems with the location provider!", Toast.LENGTH_SHORT);
			}
			else if (isNetworkEnabled){
				lm.requestLocationUpdates(lm.NETWORK_PROVIDER, MIN_TIME_BETWEEN_UPDATES, MIN_DISTANCE_FOR_UPDATES, this);
				if (lm != null){
					location=lm.getLastKnownLocation(lm.NETWORK_PROVIDER);
					if (location != null){
						latitude=location.getLatitude();
						longitude=location.getLongitude();
						Geocoder coder=new Geocoder(mContext);
						address=coder.getFromLocation(latitude, longitude, 1).get(0);
					}
					else{
						Toast.makeText(mContext, "No location available!", Toast.LENGTH_SHORT);
					}
				}
				else
					Toast.makeText(mContext, "Problems with the location provider!", Toast.LENGTH_SHORT);
			}
			
		}
		}
		catch (Exception e){
			e.printStackTrace();	
		}
		return location;

	}
	
	public double getLatitude(){
		if (location != null){
			latitude = location.getLatitude();
		}
		return latitude;
	}
	public double getLongitude(){
		if (location != null){
			longitude = location.getLongitude();
		}
		return longitude;
	}
	public String getAddress(){
		if (address!=null)
			return address.getLocality()+","+address.getSubAdminArea()+","+address.getCountryName();
		else
			return "";
	}
	
	public void stopGPS(){
        if(lm != null){
            lm.removeUpdates(GPSUtil.this);
        }       
    }
	public boolean canGetLocation(){
		return this.canGetLocation;
	}
	public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
      
        // Setting Dialog Title
        alertDialog.setTitle("GPS settings");
  
        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
  
        // Setting Icon to Dialog
        //alertDialog.setIcon(R.drawable.delete);
  
        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });
  
        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
        });
  
        // Showing Alert Message
        alertDialog.show();
    }
	
	@Override
	public void onLocationChanged(Location arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderDisabled(String arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
}
